package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.mapper.GrindingRecordMapper;
import com.yupi.springbootinit.model.dto.grinding.GrindingRecordAddRequest;
import com.yupi.springbootinit.model.dto.grinding.GrindingRecordQueryRequest;
import com.yupi.springbootinit.model.dto.grinding.GrindingRecordUpdateRequest;
import com.yupi.springbootinit.model.entity.GrindingRecord;
import com.yupi.springbootinit.model.vo.GrindingRecordVO;
import com.yupi.springbootinit.service.GrindingRecordService;
import com.yupi.springbootinit.service.ProcessSheetService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 磨床记录服务实现
 */
@Service
@Slf4j
public class GrindingRecordServiceImpl extends ServiceImpl<GrindingRecordMapper, GrindingRecord>
        implements GrindingRecordService {

    @Resource
    private ProcessSheetService processSheetService;

    @Override
    public Long addRecord(GrindingRecordAddRequest addRequest) {
        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        // 参数校验
        validateAddParams(addRequest);

        GrindingRecord record = new GrindingRecord();
        BeanUtils.copyProperties(addRequest, record);

        // 如果没有指定工艺单号，根据产品名称自动查询
        if (StringUtils.isNotBlank(addRequest.getProductName()) && StringUtils.isBlank(addRequest.getProcessSheetNo())) {
            Map<String, Object> processSheetInfo = processSheetService.queryProcessSheetByProductName(addRequest.getProductName());
            record.setProcessSheetNo((String) processSheetInfo.get("processSheetNo"));
        }

        boolean result = this.save(record);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加记录失败");
        }

        return record.getId();
    }

    @Override
    public Boolean updateRecord(GrindingRecordUpdateRequest updateRequest) {
        if (updateRequest == null || updateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }

        // 检查记录是否存在
        GrindingRecord oldRecord = this.getById(updateRequest.getId());
        if (oldRecord == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "记录不存在");
        }

        GrindingRecord record = new GrindingRecord();
        BeanUtils.copyProperties(updateRequest, record);

        boolean result = this.updateById(record);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新记录失败");
        }

        return true;
    }

    @Override
    public Boolean deleteRecord(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "记录ID错误");
        }

        // 检查记录是否存在
        GrindingRecord record = this.getById(id);
        if (record == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "记录不存在");
        }

        boolean result = this.removeById(id);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除记录失败");
        }

        return true;
    }

    @Override
    public GrindingRecordVO getRecordById(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "记录ID错误");
        }

        GrindingRecord record = this.getById(id);
        if (record == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "记录不存在");
        }

        return entityToVO(record);
    }

    @Override
    public Page<GrindingRecordVO> pageRecords(GrindingRecordQueryRequest queryRequest) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询参数为空");
        }

        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();

        // 构建查询条件
        QueryWrapper<GrindingRecord> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(queryRequest.getProcessSheetNo())) {
            queryWrapper.eq("process_sheet_no", queryRequest.getProcessSheetNo());
        }
        if (StringUtils.isNotBlank(queryRequest.getMachineNo())) {
            queryWrapper.eq("machine_no", queryRequest.getMachineNo());
        }
        if (StringUtils.isNotBlank(queryRequest.getProductName())) {
            queryWrapper.like("product_name", queryRequest.getProductName());
        }
        if (StringUtils.isNotBlank(queryRequest.getSubstrateNo())) {
            queryWrapper.eq("substrate_no", queryRequest.getSubstrateNo());
        }
        if (StringUtils.isNotBlank(queryRequest.getOperator())) {
            queryWrapper.like("operator", queryRequest.getOperator());
        }
        if (queryRequest.getStartDate() != null) {
            queryWrapper.ge("usage_date", queryRequest.getStartDate());
        }
        if (queryRequest.getEndDate() != null) {
            queryWrapper.le("usage_date", queryRequest.getEndDate());
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc("create_time");

        // 分页查询
        Page<GrindingRecord> page = this.page(new Page<>(current, pageSize), queryWrapper);

        // 转换为VO
        Page<GrindingRecordVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        voPage.setRecords(page.getRecords().stream().map(this::entityToVO).collect(java.util.stream.Collectors.toList()));

        return voPage;
    }

    /**
     * 实体转VO
     */
    private GrindingRecordVO entityToVO(GrindingRecord record) {
        if (record == null) {
            return null;
        }
        GrindingRecordVO vo = new GrindingRecordVO();
        BeanUtils.copyProperties(record, vo);
        return vo;
    }

    /**
     * 参数校验
     */
    private void validateAddParams(GrindingRecordAddRequest addRequest) {
        if (addRequest.getUsageDate() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "使用日期不能为空");
        }
        if (StringUtils.isBlank(addRequest.getProductName())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "产品名称不能为空");
        }
        if (StringUtils.isBlank(addRequest.getMachineNo())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "机台号不能为空");
        }
        if (addRequest.getStartTime() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开始时间不能为空");
        }
        if (StringUtils.isBlank(addRequest.getOperator())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "操作人不能为空");
        }
    }
}